//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;

using NHibernate.Criterion;

using ProjectBase.Core;
using ProjectBase.Data;

using Survey.Common;
using Survey.Entity;

namespace Survey.Data
{
    /// <summary>
    ///     Only DATA layer special base class.
    ///     This allows to have some code lists (Product, Country, Currency)
    ///     in the special table with small int as ID column. It can save lot of space in the storage
    ///     (Smaller sister is TINY - with tinyint as ID column)
    /// </summary>
    /// <typeparam name = "T"></typeparam>
    public abstract class CodeListSmallDao<T> : CodeListBaseDao<T, CodeListFilter>
        where T : class, ICodeList
    {
        /// <summary>
        ///     Sets the ID to the last + 1
        /// </summary>
        /// <param name = "entity"></param>
        /// <returns></returns>
        public override T Add(T entity)
        {
            var last = GetEntityWithMaxId();
            entity.SetId((last.Is() ? last.ID + 1 : 1));
            entity = base.Add(entity);
            //Session.Flush();
            return entity;
        }

        /// <summary>
        ///     Gets the Last used ID
        /// </summary>
        /// <returns></returns>
        protected virtual CodeListSmall GetEntityWithMaxId()
        {
            return Session
                .CreateCriteria(typeof(CodeListSmall))
                .AddOrder(new Order(Str.Common.ID, false))
                .SetMaxResults(1)
                .UniqueResult<CodeListSmall>();
        }
    }
}